<template>
  <div class="page-container">

    <!--工具栏-->
    <div class="toolbar" style="padding-top:10px">
      <div v-if="isView == 1" style="border: 1px solid #DCDFE6;width: 40%;">
          <el-form :inline="true" size="medium" label-widt="80" class="viewForm">
            <el-form-item label="角色名称：">
                <span class="color333 font26">{{dataForm.roleName}}</span>
            </el-form-item>
            <el-form-item label="审核状态：">
                <span class="color333 font26" v-if="dataForm.status == 1">待提交</span>
                <span class="color333 font26" v-if="dataForm.status == 2">待审核</span>
                <span class="color333 font26" v-if="dataForm.status == 3">审核通过</span>
                <span class="color333 font26" v-if="dataForm.status == 4">审核不通过</span>
            </el-form-item>
          </el-form>
          <el-row class="view-button">
              <kt-button label="提交审核" style="text-align: center;" size="small" v-if="dataForm.status == 1 || dataForm.status == 4"  @click="submitReview(dataForm)" />
              <kt-button label="撤销提交" style="text-align: center;" size="small" v-if="dataForm.status == 2 "  @click="revokeReview(dataForm)" />
              <kt-button label="审核" style="text-align: center;" size="small" v-if="dataForm.status == 2" @click="reviewSysRole(dataForm)" />
          </el-row>
      </div>
      <el-form
        :model="dataForm"
        label-width="100px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        <el-row class="search-input">
          <el-form-item label="ID" prop="id" v-if="false">
            <el-input clearable
              v-model="dataForm.id"
              :disabled="true"
              auto-complete="off"
              placeholder="请输入ID"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色名称：" prop="roleName">
            <el-input maxlength="30" v-model="dataForm.roleName" clearable placeholder="请输入角色名"></el-input>
          </el-form-item>
          <!-- <el-form-item label="所属组织：">
            <treeselect style="width: 300px" :options="options" v-model="selectName" :disabled="id!=0" noChildrenText="" :normalizer="normalizer" placeholder="请选择" noResultsText="暂无数据" searchable @select="selectDept"/>
          </el-form-item> -->
          <el-form-item label="操作权限：">
            <el-tree
          :data="menuData"
          size="mini"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          style="width: 100%;pading-top:20px;font-size:14px"
          ref="menuTree"
          :render-content="renderContent"
          v-loading="menuLoading"
          element-loading-text="拼命加载中"
        ></el-tree>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :size="size" @click="cancelRoleAdd" v-if="isView != 1">取消</el-button>
        <!-- <kt-button
          icon="fa fa-refresh" :label="$t('action.reset')"
          type="primary"
          :plain="true"
          @click="resetSelection"
        /> -->
        <kt-button :label="$t('action.submit')" type="primary" v-if="isView != 1" @click="submitAuthForm" :loading="authLoading"/>
      </div>
    </div>

    <!-- 审核弹窗 -->
    <el-dialog class="el-dialog-style" title="审核" :visible.sync="dialogFormVisible" width="30%">
        <el-form :model="verifyForm">
          <el-form-item label="审核结果：" label-width="125px">
            <el-radio-group v-model="verifyForm.status">
              <el-radio :label="3">审核通过</el-radio>
              <el-radio :label="4">审核不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核不通过原因：" label-width="125px">
              <el-input :rows="4" clearable v-model="verifyForm.remark" autocomplete="off" type="textarea" style="min-height: 33px; max-width: 75%; "></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" plain @click="dialogFormVisible = false" size="mini" class="cancelButton">取消</el-button>
            <el-button type="primary" @click="reviewDialog()" size="mini" class="searchButton">确认</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import KtButton from "@/views/Core/KtButton";
import TableTreeColumn from "@/views/Core/TableTreeColumn";
import { format } from "@/utils/datetime";
import utils from "@/assets/js/utils.js";
// import the component
import Treeselect from "@riophae/vue-treeselect";
// import the styles
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: {
    KtButton,
    TableTreeColumn,
    Treeselect
  },
  data() {
    return {
      size: "small",
      menu: {},

      operation: false, // true:新增, false:编辑
      dialogVisible: false, // 新增编辑界面是否显示
      editLoading: false,
      dataFormRules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" }
        ],
        type: [{ required: true, message: "请选择所属平台", trigger: "change" }]
      },
      // 新增编辑界面数据
      dataForm: {
        id: 0,
        roleName: "",
        remark: "",
        type: "0"
      },
      id: this.$route.params.id,
      isView: this.$route.params.view,
      selectRole: {},
      menuData: [],
      menuSelections: [],
      menuLoading: false,
      authLoading: false,
      checkAll: false,
      currentRoleMenus: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      options: [
        { value: 0, label: "运营平台" },
        { value: 1, label: "商家平台" },
        { value: 2, label: "供应商平台" }
      ],
      selectName: null,
      selectDepart: {},
      options: [],
      types: this.$route.params.types,
      
      dialogFormVisible: false,
      verifyForm:{
        status:"",
        remark:""
      },
    };
  },
  methods: {
    normalizer(node) {
      return {
        id: node.id,
        label: node.deptName,
        children: node.children,
      }
    },
    cancelRoleAdd() {
      this.$router.push({ path: "/pages/sys/SysRole" });
    },
    // 获取当前选中部门的名称
    selectDept(val) {
      console.log("selectDepart", val);
      this.selectDepart = val;
      this.handleRoleSelectChange(val);
    },
    findDeptTree() {
      var that = this;
      this.utils.request.getAuthorDeptTree({}, res => {
        if (res.code == "0000") {
          that.options = res.data;
        }
      });
      if (this.id == 0) {
        this.selectDepart = {};
        if (this.$refs["dataForm"] != undefined) {
          this.$refs["dataForm"].resetFields();
        }
      } else {
        this.handleEdit();
      }
    },
    // 显示编辑界面
    handleEdit: function() {
      var this_ = this;
      // params.row.type = params.row.type+"";
      if (this.$refs["dataForm"] != undefined) {
        this.$refs["dataForm"].resetFields();
      }
      var query = {};
      query.roleid = this.id;
      this.menu.roleid = this.id;
      this.menu.type = 0;
      if (this.selectDepart != null && this.types == 0 && this.id == 0) {
        this.menu.type = this.selectDepart.deptType;
      } else {
        this.menu.type = this.types;
      }
      this.utils.request.getRoleInfo({ id: this.id }, res => {
        if (res.code == "0000") {
          this_.dataForm = res.data;
          var arry = [];
          arry.push(res.data.deptId);
          this.selectName = arry;
        }
      });
      this.utils.request.findMenuTreeKas(this.menu, function(data) {
        this_.menuData = data.data;
        this_.utils.request.queryMenusByRoleId(query, function(data) {
          if (data.data && data.data.length > 0) {
            this_.currentRoleMenus = data.data;
            data.data.forEach(item => {
              this_.$refs.menuTree.setChecked(item, true, false);
            });
          } else {
            this_.currentRoleMenus = [];
            this_.$refs.menuTree.setCheckedNodes(this_.currentRoleMenus);
          }
        });
      });
    },
    // // 获取数据
    findTreeData: function() {
      this.menuLoading = true;
      var this_ = this;
      this.menu.type = 0;
      this.utils.request.findRoleMenuTree(this.menu, function(data) {
        this_.menuData = data.data;
        this_.menuLoading = false;
      });
    },
    //递归添加disabled
    traverseTree(menuData){
      menuData.forEach(menu => {
        menu.disabled = true
        if(menu.children){
          this.traverseTree(menu.children);
        }
      });
    },
    // 角色选择改变监听
    handleRoleSelectChange(val) {
      if (val == null) {
        return;
      }
      var query = {};
      var this_ = this;
      // this.menu.type = val.deptType;
      //默认查询所有菜单
      this.menu.type = 0;
      this.utils.request.findMenuTreeKas(this.menu, function(data) {
        this_.menuData = data.data;
        if(this_.isView == 1){//查看递归添加disabled
          this_.traverseTree(this_.menuData);
        }
      });
      if (this.id == 0) {
        this.selectDepart = {};
        if (this.$refs["dataForm"] != undefined) {
          this.$refs["dataForm"].resetFields();
        }
      } else {
        this.handleEdit();
      }
    },
    // 树节点选择监听
    handleMenuCheckChange(data, check, subCheck) {
      if (check) {
        // 节点选中时同步选中父节点
        let parentId = data.pid;
        this.$refs.menuTree.setChecked(parentId, true, true);
      } else {
        // 节点取消选中时同步取消选中子节点
        if (data.children != null) {
          data.children.forEach(element => {
            this.$refs.menuTree.setChecked(element.id, false, false);
          });
        }
      }
    },
    // 重置选择
    resetSelection() {
      this.checkAll = false;
      this.$refs.menuTree.setCheckedKeys([]);
    },
    // 全选操作
    handleCheckAll() {
      if (this.checkAll) {
        let allMenus = [];
        this.checkAllMenu(this.menuData, allMenus);
        this.$refs.menuTree.setCheckedNodes(allMenus);
      } else {
        this.$refs.menuTree.setCheckedNodes([]);
      }
    },
    // 递归全选
    checkAllMenu(menuData, allMenus) {
      menuData.forEach(menu => {
        allMenus.push(menu);
        if (menu.children) {
          this.checkAllMenu(menu.children, allMenus);
        }
      });
    },
    // 角色菜单授权提交
    submitAuthForm() {
      var this_ = this;
      let roleId = this.selectRole.id;
      let checkedNodes = this.$refs.menuTree.getCheckedNodes(false, true);
      let roleMenus = [];
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            this.authLoading = true;
            if (checkedNodes.length == 0) {
              this_.$message({
                message: "请选择角色菜单授权",
                type: "success"
              });
              this_.authLoading = false;
              return false;
            }
            for (let i = 0, len = checkedNodes.length; i < len; i++) {
              let roleMenu = { roleid: roleId, menuid: checkedNodes[i].id };
              roleMenus.push(roleMenu);
            }
            // let params = Object.assign({}, this.dataForm);
            // params.roleMenus = JSON.stringify(roleMenus);
            // params.roleMenusList = roleMenus;
            // params.type = this.selectDepart.deptType;
            // params.deptId = this.selectDepart.id;
            let params = {
              'operateType': this.id==0?'1':'2',
              'roleid': this.dataForm.id,
              'roleName': this.dataForm.roleName,
            };
            let modifyText = {
              'roleMenusList': JSON.stringify(roleMenus),
              'deptId': this.selectDepart.id,
              'businessId': this.selectDepart.businessId,
              'type': 0,//默认层级为 0 
              'id':this.id,
            }
            params.modifyText = JSON.stringify(modifyText);
            this.utils.request.addSysRoleMenuVerify(params, function(data) {
              if (data.code == "0000") {
                this_.$message({ message: "操作成功", type: "success" });
                this_.authLoading = false;
                this_.dialogVisible = false;
                this_.operation = false;
                this_.editLoading = false;
                this_.$router.push({ path: "/pages/sys/SysRole" });
                // this_.menuData = [];
              } else {
                this_.authLoading = false;
                this_.$message({
                  message: data.msg,
                  type: "error"
                });
              }
            });
          });
        }
      });
    },
    renderContent(h, { node, data, store }) {
      return (
        <div class="column-container">
          <span style="text-algin:center;margin-right:200px; width:100px">
            {data.name}
          </span>
          <span style="text-algin:center;margin-right:100px;">
            <el-tag
              type={data.types == 0 ? "" : data.types == 1 ? "success" : "info"}
              size="small"
            >
              {data.types == 0 ? "目录" : data.types == 1 ? "菜单" : "按钮"}
            </el-tag>
          </span>
          <span style="text-algin:center;margin-right:200px;">
            {" "}
            <i class={data.icon} />
          </span>
          <span style="text-algin:center;margin-right:80px;">
            {data.parentName ? data.parentName : "顶级菜单"}
          </span>
          <span style="text-algin:center;margin-right:80px;" />
        </div>
      );
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      if (true) {
        return "llll";
      }
      return format(row[column.property]);
    },
    
    // 1-2 提交审核 
    submitReview(val){
      let that = this; 
      //判断状态是否为待提交
      if(val.status != 1 && val.status != 4){
        that.$message({ message: "当前状态不可操作",   type: "warning"});
        return false;
      }
      that.utils.request.submitReview(val , res => {
        if(res.code == "0000"){
          that.$message({ message: "操作成功",   type: "success"});
          that.handleEdit();
        }else if(res.code == "9999") {
          that.$message({ message: res.msg,   type: "error"});
        }
      });
      
    },
    // 2-1 撤销提交 
    revokeReview(val){
      let that = this; 
      //判断状态是否为待审核
      if(val.status != 2){
        that.$message({ message: "当前状态不可操作",   type: "warning"});
        return false;
      }
      that.utils.request.revokeReview(val , res => {
        if(res.code == "0000"){
          that.$message({ message: "操作成功",   type: "success"});
          that.handleEdit();
        }else if(res.code == "9999") {
          that.$message({ message: + res.msg,   type: "error"});
        }
      });
      
    },
    //3 审核
    reviewSysRole(val){
      //默认通过
      this.$nextTick(() => {
        this.verifyForm = {};
        this.verifyForm.status = 3;
        this.verifyForm.id = val.id;
        this.verifyForm.remark = '';
        this.verifyForm.type = false;
        this.dialogFormVisible = true;
      });
    },
    //审核弹窗
    reviewDialog(){
      let that = this;
      if(that.verifyForm.type){
        that.utils.request.batchRoleReview(this.verifyForm, res=>{
          if(res.code == "0000"){
            that.$message({ message: "操作成功",   type: "success"});
            that.handleEdit();
            that.dialogFormVisible = false;
          }else if(res.code == "9999") {
            that.$message({ message: + res.msg,   type: "error"});
          }
          this.verifyForm = {remark:""};
        });
      }else {
        that.utils.request.roleReview(this.verifyForm, res=>{
          if(res.code == "0000"){
            that.$message({ message: "操作成功",   type: "success"});
            that.handleEdit();
            that.dialogFormVisible = false;
          }else if(res.code == "9999") {
            that.$message({ message: + res.msg,   type: "error"});
          }
          this.verifyForm = {remark:""};
        });
      }
    },
  },
  mounted() {
    // this.findDeptTree();
    this.handleRoleSelectChange(0);
  }
};
</script>
<style scoped lang="scss">
.menu-container {
  margin-top: 10px;
}
.menu-header {
  padding-left: 8px;
  padding-bottom: 5px;
  text-align: left;
  font-size: 16px;
  color: rgb(20, 89, 121);
}
/deep/ .vue-treeselect__input {
  max-width: 100%;
  margin: 0;
  padding: 0;
  border: 0;
  outline: none;
  -webkit-box-sizing: content-box;
  box-sizing: content-box;
  -webkit-box-shadow: none;
  box-shadow: none;
  background: none transparent;
  line-height: 1;
  vertical-align: middle;
}
/deep/ .search-input .el-form-item__content .el-input__inner {
  width: 300px !important;
}
/deep/ .column-container{
  span{
    display: inline-block;
    width: 84px;
  }
  /deep/ .el-tag.el-tag--success{
    width:auto;
  }
  /deep/ .el-tag.el-tag--info{
    width: auto ;
  }
  
}
.search-input{
  margin-bottom: 173px;
}
.viewForm{
  margin-left: 10%;
  margin: 5% 5% 5% 5%;
  /deep/ .el-form-item__label{
    font-size: 22px;
  }
  /deep/ .el-form-item__content{
    font-size: 22px;
  }
}
.view-button{
  text-align: left;
  width: 100%;
  -webkit-box-pack: end;
  -ms-flex-pack: end;
  justify-content: flex-end;
  margin-left: 5%;
  margin-bottom: 5%;
}
</style>
